<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Menu;
use app\admin\model\Role;
use think\Request;
use think\Session;

class Admins extends Base
{
    /*
     * 后台加载首页用户中心
     */
    public function admin(){
        $user = $this->user_info();

        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$user,
        );
        return view("admin",$data);
    }
    /*
     * 用户列表
     */
    public function lists(){
        $user = $this->user_info();
        //查询所有用户
        $users = collection(Admin::select())->toArray();

        foreach($users  as $key=>$val){
              //查询每个用户的权限
              //查询所属的角色
              $roles = Role::where(array("r_id"=>$val['roles_id']))->find();
              $users[$key]['roles'] = $roles['r_name'];
              //查询角色的顶级权限
               $jurisdiction = collection(Menu::where(array('pid'=>0,"id"=>array('in',$roles['jurisdiction'])))->order("sort asc")->select())->toArray();
               foreach($jurisdiction as $k=>$v){
                   $jurisdiction2 = Menu::where(array("pid"=>$v['id'],"id"=>array("in",$roles['jurisdiction'])))->select();
                   //将查询出来的第二层放在第一层中
                   $jurisdiction[$k]['jurisdiction2'] = collection($jurisdiction2)->toArray();
               }
               $users[$key]['jurisdictions'] = $jurisdiction;
               //添加上级领导名称
               $users[$key]['parent'] = "无";
               foreach($users as $v){
                   if($val['pid'] == $v['id']) {
                       $users[$key]['parent'] = $v['username'];
                       break;
                   }
               }
        }


        $data = array(
            "setting" => $this->getAllSetting(),
            "user" =>$user,
            "list" =>$users,
            "roles" =>$roles
        );
        return view("list",$data);
    }
    /*
     * 添加用户
     */
    public function addform()
    {
        $user = $this->user_info();
        $roles = collection(Role::select())->toArray();
        //查询第一个角色下的所有用户
        $admins = Admin::where(['roles_id'=>$roles[0]['r_id']])->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$user,
            "rols" =>$roles,
            "admins"=>$admins,
        );
        return view("addform",$data);
    }
    /*
     * 执行添加操作
     */
    public function adds(Request $request){
        $data = $request->post();
        $data['password'] = md5($data['password']);
        $data['create_time'] = time();
        $data['create_ip'] = $_SERVER['REMOTE_ADDR'];
        //查询用户名是否重复
        $res = Admin::where(array("username"=>$data['username']))->count();
        if($res > 0){
            $this->error("该用户名已经存在!请更换用户名再试！");
            exit();
        }
        if(Admin::insert($data)){
            $this->success("添加成功","Admins/lists");
        }else{
            $this->error("添加失败");
        }
    }
    /*
     * 修改用户
     */
    public function update(Request $request){
        $user = $this->user_info();
        $id = $request->get("id");
        //查询当前需要修改的用户
        $admin = Admin::where(['id'=>$id])->find();
        //查询所有的角色
        $rols = Role::select();
        //找到领导的角色id
        $pid = "";
        foreach($rols as $v){
            if($v['r_id'] == $admin['roles_id']){
                $pid = $v['pid'];
                break;
            }
        }
        //查询所有上一级所有领导的用户
        $ld = Admin::where(array("roles_id"=>$pid))->field("id,pid,username")->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" =>$admin,
            "rols" => $rols,
            "user" => $user,
            "ld" => $ld,
        );
        return view("update",$data);
    }
    /*
     * 查询当前角色的
     */
    public function getld(Request $request){
        $pid = $request->post("pid");
        //查询当前角色
        $users = Admin::where(array("roles_id"=>$pid))->select();
        $str = "";
        if(empty($users)){
            return $str;
        }else{
            foreach($users as $v){
                $str .= "<option value='".$v['id']."'>".$v['username']."</option>";
            }
            return $str;
        }
    }
    /*
     * 执行修改
     */
    public function toupdate(Request $request){
        $user = $this->user_info();
        $data = $request->post();

        if (!empty($data['password'])){
            $data['password'] = md5($data['password']);
        }
        if(Admin::update($data)){
            //如果是当前用户直接修改Session值
            if($data['username'] == $user['username']){
                $newUser = Admin::where(array('id'=>$user['id']))->find();
                Session::delete("user_info");
                Session::set("user_info",$newUser);
            }
            $this->success("修改成功","Admins/lists");
        }else{
            $this->error("修改失败","Admins/update");
        }
    }
    /*
     * 删除
     */
    public function deletes(Request $request){
        $id = $request->post("id");
        if(Admin::destroy(["id"=>$id])){
            $this->success("删除成功","Admins/lists");
        }else{
            $this->error("删除失败");
        }
    }
    /*
     *上传文件
     */
    public function upload(Request $request){
        //接收上传的文件
        $file = $this->request->file('file');
        if(!empty($file)){
            //图片存的路径
            $imgUrl= ROOT_PATH . 'public' . DS .'static'. DS .'admin'. DS .'uploads'. DS .'headphoto';
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->rule('uniqid')->move($imgUrl);
            $error = $file->getError();
            //验证文件后缀后大小
            if(!empty($error)){
                dump($error);exit;
            }
            if($info){
                //获取图片的名字
                $imgName = $info->getFilename();
                //获取图片的路径
                $photo= $imgName;
            }else{
                // 上传失败获取错误信息
                $file->getError();
            }
        }else{
            $photo = '';
        }
        if($photo !== ''){
            return ['code'=>1,'msg'=>'成功','photo'=>$photo];
        }else{
            return ['code'=>404,'msg'=>'失败'];
        }
    }


    //修改密码
    /**
     * Undocumented function
     * @param  $name
     *
     * @return void
     */
    public function setpassword(){
        $user = $this->user_info();
        $data = array(
            "setting" => $this->getAllSetting(),
        );
        return view("setpassword",$data);
    }
    //执行修改密码
    public function toSetPassword(Request $request){
        $oldpassword = $request->post("oldpassword");

        $password = $request->post("password");
        //判断用户是否正确可以登录
        $user = $this->user_info();
        if(md5($oldpassword) == $user['password']){
            if(Admin::update(array("id"=>$user['id'],"password"=>md5($password)))){
                $this->success("密码修改成功，请重新登录","Login/index");
            }else{
                $this->error("密码修改失败","Set/setpassword");
            }
        }else{
            $this->error("旧密码错误");
        }
    }
}
